package com.websuites.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharsetFilter implements Filter
{
	protected String encoding = null;
	protected FilterConfig filterConfig = null;
	protected boolean ignore = true;
	private String ignoreControl = "";

	public void destroy()
	{
		this.encoding = null;
		this.filterConfig = null;
		this.ignoreControl = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		if (ignore || (request.getCharacterEncoding() == null))
		{
			if (!this.ignoreControl.equals(""))
			{
				HttpServletRequest req = (HttpServletRequest)request;
				String sURI = req.getRequestURI().toString();
				String sContextPath = req.getContextPath();
				
				String sShortURI = sURI.substring(sContextPath.length());
				
				Pattern p = Pattern.compile(this.ignoreControl);
				Matcher m = p.matcher(sShortURI);
	
				if (!m.find())
				{
					request.setCharacterEncoding(this.encoding);
				}
			}
			else
			{
				request.setCharacterEncoding(this.encoding);
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException
	{
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		String sIgnoreControl = filterConfig.getInitParameter("ignore-control");
		if (value == null)
		{
			this.ignore = true;
		}
		else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))
		{
			this.ignore = true;
		}
		else
		{
			this.ignore = false;
		}
		if (sIgnoreControl == null)
		{
			this.ignoreControl = "";
		}
		else
		{
			this.ignoreControl = sIgnoreControl;
		}
	}

	public FilterConfig getFilterConfig()
	{
		return filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig)
	{
		this.filterConfig = filterConfig;
	}
}